import React, { memo } from "react";
import { Upload, message, Button } from "antd";
import { UploadOutlined } from "@ant-design/icons";
import http from "utils/http";
import { asyncPool } from "utils";

const SIZE = 100 * 1024 * 1024;//设置切片的大小

export default memo(function UploadT() {
  let filename = "";
  let hash = "";
  let worker = "";
  const Uploadfile = async (data) => {
    const { file, onSuccess } = data;
    console.log(data);
    if (!file) {
      message("请选择文件！");
      return;
    }
    // let temp = file?.name.split('.').pop()
    // filename = file?.name.replace('.' + temp,'')
    filename = file?.name;
    //创建文件分片
    const fileChunkList = createFileChunk(file);
    //计算文件hash
    hash = await calculateHash(fileChunkList);
    //查询服务端之前是否上传过
    let result = await contrastFile(filename, hash,SIZE);
    let chunkPaths = [];
    if (result && result.data) {
      message.success("秒传成功!");
      if (Array.isArray(result.data)) {
        let temparr = result.data;
        temparr.sort((a, b) => a.split("-$$-")[1] - b.split("-$$-")[1]);
        chunkPaths = temparr
        //chunkPaths = temparr.slice(0, temparr.length - 1); //舍弃最后的一个分片
      }
      onSuccess();
      return;
    }
    //给分片排序 防止服务端流写错顺序
    const filedatalist = fileChunkList.map((item, index) => ({
      chunk: item.file,
      hash: `${hash}-$$-${index}`,
    }));
    //调用上传文件方法
    console.log(filedatalist)
    console.log(chunkPaths)
    await uploadChunks(filedatalist, chunkPaths);
    onSuccess();
    message.success("上传成功!");
  };

  //上传文件
  const uploadChunks = async (data, exist) => {
    //排除上传过的分片
    data = data.filter((r) => !exist.includes(r));
    const datalist = data.map((item) => {
      let formData = new FormData();
      formData.append("chunk", item.chunk);
      formData.append("hash", item.hash);
      formData.append("filename", filename);
      formData.append("filehash", hash);
      return { formData };
    });


    /* await Promise.all(
      datalist.map(({ formData }) => http.post("/upload", formData))
    ); */
    await asyncPool(3,datalist,({formData})=> http.post("/upload", formData))
    await mergeRequest(filename);
  };

  //文件秒传
  const contrastFile = async (filename, filehash,size) => {
    return await http.post("/contrast", { filename, filehash ,size});
  };

  // 生成文件切片
  const createFileChunk = (file, size = SIZE) => {
    const fileChunkList = [];
    let cur = 0;
    while (cur < file.size) {
      fileChunkList.push({ file: file.slice(cur, cur + size) });
      cur += size;
    }
    return fileChunkList;
  };

  //生成文件hash
  const calculateHash = (fileChunkList) => {
    return new Promise((resolve) => {
      // 添加 worker 属性
      worker = new Worker("/hash.js");
      worker.postMessage({ fileChunkList });
      worker.onmessage = (e) => {
        const { hash } = e.data;
        //percentage 计算的总进度

        if (hash) {
          resolve(hash);
        }
      };
    });
  };

  //合并文件分片
  const mergeRequest = async (filename) => {
    await http.post("/merge", {
      size: SIZE,
      filename,
      filehash: hash,
    });
  };

  return (
    <div>
      <Upload customRequest={Uploadfile}>
        <Button icon={<UploadOutlined />}>点击上传</Button>
      </Upload>
    </div>
  );
});
